package com.yuanshi.food.common.entity;

import com.yuanshi.food.common.enums.ResponseCodeEnum;
import com.yuanshi.food.common.exception.AppException;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * 响应
 *
 * @author wcy
 * @date 2024/11/26
 */
@Data
@Builder(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Schema(title = "响应")
public class Response<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 7000723935764546321L;
    @Schema(title = "响应编码")
    private Integer code;
    @Schema(title = "响应信息")
    private String info;
    @Schema(title = "响应数据")
    private T data;

    public static Response<Void> failVoid() {
        return getResponseVoid(ResponseCodeEnum.UN_ERROR.getCode(), ResponseCodeEnum.UN_ERROR.getInfo());
    }

    public static Response<Void> successVoid() {
        return getResponseVoid(ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getInfo());
    }

    public static <T> Response<T> fail() {
        return getResponse(ResponseCodeEnum.UN_ERROR.getCode(), ResponseCodeEnum.UN_ERROR.getInfo(), null);
    }

    public static <T> Response<T> fail(String info, T data) {
        return Response.getResponse(ResponseCodeEnum.UN_ERROR.getCode(), info, data);
    }

    public static <T> Response<T> success() {
        return getResponse(ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getInfo(), null);
    }

    public static <T> Response<T> success(T data) {
        return Response.getResponse(ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getInfo(), data);
    }

    public static <T> Response<T> build(ResponseCodeEnum responseCodeEnum) {
        return getResponse(responseCodeEnum.getCode(), responseCodeEnum.getInfo(), null);
    }

    public static <T> Response<T> build(ResponseCodeEnum responseCodeEnum, T data) {
        return Response.getResponse(responseCodeEnum.getCode(), responseCodeEnum.getInfo(), data);
    }

    public static Response<String> appException(AppException ex) {
        return Response.getResponse(ex.getCode(), ex.getInfo(), ex.getMessage());
    }

    private static <T> Response<T> getResponse(Integer code, String info, T data) {
        return Response.<T>builder()
                       .code(code)
                       .info(info)
                       .data(data)
                       .build();
    }

    public static Response<Void> getResponseVoid(Integer code, String info) {
        return Response.<Void>builder()
                       .code(code)
                       .info(info)
                       .build();
    }

}
